package hackthon.core;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * Created by wuwenhao on 15/1/7.
 */
public class MailSender {

    public String username;
    public String password;
    public String subject;
    public String host;
    public String send_from;
    public String send_to;
    public String mail_body;

    public void sendMail(String email, String password, String send_to, String content) throws SendFailedException {
        try {
            Properties props = new Properties();
            MailAuthenticator auth = new MailAuthenticator(email,password);
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");
            System.out.println(props);
            Session session = Session.getDefaultInstance(props, auth);
            MimeMessage message = new MimeMessage(session);
            message.setContent("Hello", "text/plain");
            message.setSubject(subject);
            message.setText(content);
            message.setHeader("I am mail header", "I am mail header value");
            message.setSentDate(new Date());
            Address address = new InternetAddress(send_from);
            message.setFrom(address);
            Address toAddress = new InternetAddress(send_to);
            message.addRecipient(Message.RecipientType.TO, toAddress);
            Transport.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public String getEmailHost(String emailAddress){
        String splitEmail[] = emailAddress.split("@");
        String host = "smtp." + splitEmail[1];
        return host;
    }

    public static void main(String args[]) throws SendFailedException {
        MailSender mailSender = new MailSender();
        mailSender.host="smtp.163.com";
        mailSender.mail_body="hello world";
        mailSender.subject="This is a test mail";
        mailSender.send_from="diaosino1@163.com";
        mailSender.send_to="theshaoqi@163.com";
        //mailSender.sendMail();
    }

}
